package com.drg.center.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.drg.center.dao.SysDepartDAO;
import com.drg.center.entity.SysDepartPO;
import com.drg.center.entity.result.SysDeptVO;
import com.drg.center.service.SysDeptService;
import com.guaike.core.entity.result.Result;
import com.guaike.core.utils.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author: zhangxilin
 * @Date: 2024/5/15
 */
@Slf4j
@Service
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    private SysDepartDAO sysDepartDAO;


    @Override
    public Result<List<Tree<String>>> findTree(Boolean onlyEnable) {
        List<SysDepartPO> poList = sysDepartDAO.findList(onlyEnable);
        if(CollectionUtils.isEmpty(poList)){
            return Result.success().data(Lists.newArrayList()).build();
        }
        List<SysDeptVO> list = ListUtil.copyList(poList, SysDeptVO.class);
        return Result.success().data(buildTree(list)).build();
    }


    private List<Tree<String>> buildTree(List<SysDeptVO> list){
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("departCode");
        treeNodeConfig.setParentIdKey("parentCode");
        treeNodeConfig.setNameKey("departName");
        treeNodeConfig.setWeightKey("departCode");

        return TreeUtil.build(list, null,treeNodeConfig,
                (item, tree) -> {
                    tree.setId(item.getDepartCode());
                    tree.setName(item.getDepartName());
                    tree.setParentId(item.getParentCode());
                    tree.setWeight(item.getDepartCode());
                    tree.putExtra("extra", item);
                });
    }

    @Override
    public Result<SysDeptVO> detail(String departCode) {
        SysDepartPO record = sysDepartDAO.findOne(SysDepartPO::getDepartCode, departCode);
        if(record==null){
            return Result.failure().message("部门不存在").build();
        }
        SysDeptVO vo = new SysDeptVO();
        BeanUtil.copyProperties(record,vo);
        return Result.success().data(vo).build();
    }
}
